package com.rural.bus.view;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.rural.bus.R;
import com.rural.bus.adapter.SearchAddressAdapter;
import com.rural.bus.model.MyPoiInfo;

public class SearchAddressPop extends PopupWindow {

	private Activity mContext;
	private InputMethodManager imm;

	private String mCity;
	private PoiSearch mPoiSearch;
	private SuggestionSearch mSuggestionSearch;
	private SuggestionSearchOption mSuggestionSearchOption;
	private SearchAddressAdapter mAdapter;
	private SearchCallBack mSearchCallBack;

	public SearchAddressPop(Activity context, SearchCallBack callBack) {
		mContext = context;
		mSearchCallBack = callBack;
		imm = (InputMethodManager) mContext
				.getSystemService(Context.INPUT_METHOD_SERVICE);

		View contentView = LayoutInflater.from(context).inflate(
				R.layout.pop_search_address, null);

		DisplayMetrics metrics = new DisplayMetrics();
		context.getWindowManager().getDefaultDisplay().getMetrics(metrics);

		int width = metrics.widthPixels;
		int height = metrics.heightPixels;

		setWidth(width);
		setHeight(height);
		setContentView(contentView);
		setFocusable(true);
		setBackgroundDrawable(new BitmapDrawable());
		initView(contentView);

		mCity = "";
		mPoiSearch = PoiSearch.newInstance();

		mSuggestionSearch = SuggestionSearch.newInstance();
		mSuggestionSearch
				.setOnGetSuggestionResultListener(mOnGetSuggestionResultListener);
		mSuggestionSearchOption = new SuggestionSearchOption();
		mSuggestionSearchOption.city(mCity);

		mAdapter = new SearchAddressAdapter(mContext);
		mListView.setAdapter(mAdapter);
		
	}
	
	@Override
	public void showAsDropDown(View anchor) {
		super.showAsDropDown(anchor);
		DbUtils dbUtils=DbUtils.create(mContext);
		try {
			List<MyPoiInfo> infos=dbUtils.findAll(Selector.from(MyPoiInfo.class).limit(10));
			mAdapter.appendToList(infos);
		} catch (DbException e) {
			e.printStackTrace();
		}
	}

	private ListView mListView;
	private TextView tvEmpty;
	private EditText etInput;
	private TextView btnClear;
	private TextView btnCancle;

	private void initView(View contentView) {
		mListView = (ListView) contentView.findViewById(R.id.listview);
		tvEmpty = (TextView) contentView.findViewById(R.id.tv_empty);
		etInput = (EditText) contentView.findViewById(R.id.et_input);
		btnClear = (TextView) contentView.findViewById(R.id.btn_clear);
		btnCancle = (TextView) contentView.findViewById(R.id.btn_cancle);

		btnClear.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				etInput.getEditableText().clear();
			}
		});

		btnCancle.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				dismiss();
			}
		});

		etInput.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int arg1, int arg2,
					int arg3) {
				if (s.length() > 0) {
					btnClear.setVisibility(View.VISIBLE);
					mSuggestionSearch.requestSuggestion(mSuggestionSearchOption
							.keyword(s.toString()));
				} else {
					btnClear.setVisibility(View.GONE);
					mAdapter.appendToList(null);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				MyPoiInfo address = (MyPoiInfo) mAdapter.getItem(arg2);
//				address.id=address.name;
				DbUtils dbUtils=DbUtils.create(mContext);
				try {
					MyPoiInfo info=dbUtils.findFirst(Selector.from(MyPoiInfo.class).where("name", "=", address.name));
					if(info==null||!info.address.equals(address.address)){
						dbUtils.save(address);
					}
				} catch (DbException e) {
					e.printStackTrace();
				}
				if (null != mSearchCallBack) {
					mSearchCallBack.setResult(address);
				}
				dismiss();
			}
		});
	}

	private List<SuggestionResult.SuggestionInfo> mSuggestionInfos;
	private int searchKeyCount = 0;

	private void setEmptyViewVisible(boolean flag) {
		if (flag) {
			tvEmpty.setVisibility(View.VISIBLE);
		} else {
			tvEmpty.setVisibility(View.GONE);
		}
	}

	public void show() {
		super.showAtLocation(mContext.getWindow().getDecorView(),
				Gravity.BOTTOM, 0, 0);
		etInput.requestFocus();
	}

	public void onDestory() {
		if (mPoiSearch != null) {
			mPoiSearch.destroy();
		}
		if (mSuggestionSearch != null) {
			mSuggestionSearch.destroy();
		}
		super.dismiss();
	}

	@Override
	public void dismiss() {
		etInput.getEditableText().clear();
		imm.hideSoftInputFromWindow(etInput.getWindowToken(), 0);
		setEmptyViewVisible(false);
		super.dismiss();
	}

	/**
	 * 自动建议查询
	 */
	private OnGetSuggestionResultListener mOnGetSuggestionResultListener = new OnGetSuggestionResultListener() {
		@Override
		public void onGetSuggestionResult(SuggestionResult arg0) {
			List<SuggestionResult.SuggestionInfo> allSuggestions = arg0
					.getAllSuggestions();
			if (null != allSuggestions && allSuggestions.size() > 0) {
				mSuggestionInfos = allSuggestions;
				searchKeyCount = 0;
				searchPoiWithKey(allSuggestions.get(0).key);
			} else {
				mAdapter.appendToList(null);
				setEmptyViewVisible(true);
			}
		}
	};

	/**
	 * 自动建议查询结果反解
	 * 
	 * @param keyWord
	 */
	private void searchPoiWithKey(String keyWord) {
		mPoiSearch.setOnGetPoiSearchResultListener(mListenerWithkey);
		mPoiSearch.searchInCity(new PoiCitySearchOption().city(mCity)
				.keyword(keyWord).pageCapacity(20));
	}

	/**
	 * 自动建议查询结果反解
	 */
	private OnGetPoiSearchResultListener mListenerWithkey = new OnGetPoiSearchResultListener() {
		@Override
		public void onGetPoiDetailResult(PoiDetailResult arg0) {
		}

		@Override
		public void onGetPoiResult(PoiResult arg0) {
			List<PoiInfo> allPoi = filterPoiCity(arg0.getAllPoi(), mCity);
			if (null != allPoi && allPoi.size() > 0) {
				TreeSet<MyPoiInfo> infos = new TreeSet<MyPoiInfo>();
				for (PoiInfo poiInfo : allPoi) {
					MyPoiInfo address = MyPoiInfo.parsePoi(poiInfo);
					if (null != address && !infos.contains(address)) {
						infos.add(address);
					}
				}
				mAdapter.appendToList(infos);
				setEmptyViewVisible(false);
			} else {
				if (searchKeyCount < mSuggestionInfos.size()) {
					searchPoiWithKey(mSuggestionInfos.get(searchKeyCount).key);
					searchKeyCount++;
				} else {
					mAdapter.appendToList(null);
					setEmptyViewVisible(true);
				}
			}
		}
	};

	private List<PoiInfo> filterPoiCity(List<PoiInfo> allPoi, String city) {
		List<PoiInfo> temps = null;
		if (null != allPoi && allPoi.size() > 0) {
			temps = new ArrayList<PoiInfo>();
			for (PoiInfo poiInfo : allPoi) {
				if (!TextUtils.isEmpty(poiInfo.city)
						&& poiInfo.city.contains(city)) {
					temps.add(poiInfo);
				}
			}
		}
		return temps;
	}
	
	public interface SearchCallBack {
		void setResult(MyPoiInfo address);
	}
	
	public String getInputContent(){
		String result = "";
		if (etInput != null) {
			result = etInput.getText().toString().trim();
		}
		return result;
	}
}
